//
//  PicCatViewController.m
//  YinHang
//
//  Created by 张亚哲 on 14/10/29.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "PicCatViewController.h"


@interface PicCatViewController ()<ASIHTTPRequestDelegate,UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>{
    
    __weak IBOutlet UIView *backView;
    __weak IBOutlet UIImageView *mainImage;
    __weak IBOutlet UITextField *urlTextField;
    
    ASIFormDataRequest *getMainRequest;
    ASIFormDataRequest *postSaveRequest;
    ASIFormDataRequest *postUploadFile;
    
    
    MBProgressHUD *postHud;
    
    //参数
    NSString *action;
    NSDictionary *paramsDict;
    
    NSString *filePath;//内容图片地址
    NSString *path;
    
    UIImagePickerController *imgPC;//UIImagePickerController对象
    UIImage *image;//最终的图片
    NSString *filename;
    NSString *imgFileByte;//图片上传filebyte参数
    
    BOOL changed;
    BOOL addChanged;
}

@end

@implementation PicCatViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    changed = NO;
    addChanged = NO;
    [self setUI];
    if ([_state isEqualToString:@"add"]) {
        
    }else{
        [self postAdMain];
    }
    [self setNavTitle];
    mainImage.contentMode = UIViewContentModeScaleAspectFit;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark UI Method

-(void)setNavTitle{
    //标题
    self.navigationItem.title = @"图片管理";
    //返回按钮
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
    //保存按钮
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 60, 35)];
    UIImage *postBtn_bgImg = [UIImage imageNamed:@"postbtn_bg"];
    [rightBtn setBackgroundImage:[postBtn_bgImg stretchableImageWithLeftCapWidth:postBtn_bgImg.size.width*0.5f topCapHeight:postBtn_bgImg.size.height*0.5f] forState:UIControlStateNormal];
    [rightBtn setTitle:@"保存" forState:UIControlStateNormal];
    rightBtn.layer.cornerRadius = 5.0;
    [rightBtn addTarget:self action:@selector(save:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
}
-(void)setUI{
    urlTextField.text = @"";
    backView.layer.cornerRadius = 5.0;
    //初始化单击手势
    UITapGestureRecognizer *tgrSingle = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(takePhotoTap:)];
    tgrSingle.numberOfTouchesRequired = 1; //定义需要一个手指
    tgrSingle.numberOfTapsRequired = 1; //定义需要轻拍一次
    mainImage.userInteractionEnabled = YES;
    [mainImage addGestureRecognizer:tgrSingle];
}

#pragma mark Custom Method

-(void)back{
    [_delegate reloadDate];
    [getMainRequest cancel];
    [postSaveRequest cancel];
    [postUploadFile cancel];
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)takePhotoTap:(id)sender{
    [self getPhoto];
}
//保存提交
-(void)save:(id)sender{
    if ([_state isEqualToString:@"add"]) {
        if (addChanged) {
            [self postPicInfo];
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请选择或拍摄图片" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
    }else{
        if (changed) {//图片是否改变，不改变就直接上传
            [self postPicInfo];
        }else{
            [self postInfo];
        }
    }
}
//发送请求
-(void)postInfo{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        //BOOL b = postHud.hidden;
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
//            if (postSaveRequest) {
//                postHud.hidden = NO;
//                return;
//            }
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在发布，请稍后...";
        }
        
        postSaveRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        postSaveRequest.requestMethod = @"POST";
        // 设置超时时间
        postSaveRequest.timeOutSeconds = 60;
        postSaveRequest.delegate = self;
        // 设置参数
        NSString *actionStr = [NSString string];
        if ([_state isEqualToString:@"add"]) {
            actionStr = @"Advertisementadd";
            paramsDict = @{@"uid":UNAME,@"pictureLink":urlTextField.text,@"picturePath":path};
        }else if ([_state isEqualToString:@"alterAd"]){
            actionStr = @"Advertisementupdate";
            paramsDict = @{@"uid":UNAME,@"id":_picId,@"pictureLink":urlTextField.text,@"picturePath":path};
        }else{
            actionStr = @"Useradvupdate";
            paramsDict = @{@"uid":UNAME,@"id":_picId,@"url":urlTextField.text,@"picture":path};
        }
        
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, actionStr,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        postSaveRequest.postBody = [paramsData mutableCopy];
        
        [postSaveRequest startAsynchronous];
    }
}
//发送图片上传请求
-(void)postPicInfo{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        //BOOL b = postHud.hidden;
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
//            if (postSaveRequest) {
//                postHud.hidden = NO;
//                return;
//            }
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在发布，请稍后...";
        }
        
        postUploadFile = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        postUploadFile.requestMethod = @"POST";
        // 设置超时时间
        postUploadFile.timeOutSeconds = 60;
        postUploadFile.delegate = self;
        // 设置参数
        filename = [self getCurrentDateTime];
        NSString *actionStr = @"";
        actionStr = @"fileupload1";
        filename = [NSString stringWithFormat:@"%@.png",filename];
        paramsDict = @{@"uid":UNAME,@"cid":UID,@"filename":filename,@"filebyte":imgFileByte};//uid会员名;filename文件名;filebyte文件文件（btye字节【须将字节数组转化为16进制】）
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, actionStr,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        postUploadFile.postBody = [paramsData mutableCopy];
        
        [postUploadFile startAsynchronous];
    }
}
//获取信息
-(void)postAdMain{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        if (!postHud || postHud.hidden == YES) {
            // 提示正在加载数据...
            postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            postHud.labelText = @"正在查询，请稍后...";
        }
        
        getMainRequest = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
        getMainRequest.requestMethod = @"POST";
        // 设置超时时间
        getMainRequest.timeOutSeconds = 60;
        getMainRequest.delegate = self;
        // 设置参数
        if ([_state isEqualToString:@"alterAd"]) {
            action = @"Advertisementmain";
        }else{
            action = @"Useradvmain";
        }
        paramsDict = @{@"id":_picId};//lid名;
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        getMainRequest.postBody = [paramsData mutableCopy];
        
        [getMainRequest startAsynchronous];
    }
}
#pragma mark - ASIHTTPRequestDelegate Method

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSLog(@"%@",request.responseString);
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        if (errorCode == 0) {
            postHud.hidden = YES;
            if (request == getMainRequest) {
                NSDictionary *content = result[@"info"];
                if ([_state isEqualToString:@"alterAd"]) {
                    [mainImage sd_setImageWithURL:content[@"PicturePath"] placeholderImage:PLACE_HODER_IMG];
                    urlTextField.text = content[@"PictureLink"];
                    path = content[@"PicturePath"];
                }else if([_state isEqualToString:@"alterPic"]){
                    [mainImage sd_setImageWithURL:content[@"Picture"] placeholderImage:PLACE_HODER_IMG];
                    urlTextField.text = content[@"Url"];
                    path = content[@"Picture"];
                }else{
                    mainImage.image = PLACE_HODER_IMG;
                    path = @"";
                }
            }else if(request == postUploadFile){
                // 文件（图片、视频）上传成功
                NSDictionary *info = result[@"info"];
                path = info[@"filepath"];
                [self postInfo];
            }else{
                if ([_state isEqualToString:@"add"]) {
                    [SVProgressHUD showSuccessWithStatus:@"增加成功"];
                }else{
                    [SVProgressHUD showSuccessWithStatus:@"修改成功"];
                }
                postHud = nil;
//                double delayInSeconds = 2.0;
//                dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
//                dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//                    [self.navigationController popViewControllerAnimated:YES];
//                });
//
            }
        } else {
            postHud.hidden = YES;
            [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
        }
    } else {
        postHud.hidden = YES;
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    postHud.hidden = YES;
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}

#pragma mark 选择图片
-(void)getPhoto{
    UIActionSheet *sheet;
    // 判断是否支持相机
    sheet  = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"拍照",@"从相册选择", nil];
    sheet.tag = 255;
    [sheet showInView:self.view];
}
#pragma mark UIActionSheet Delegate Method

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:{
            //NSLog(@"1");
            //取消
        }break;
        case 1:{
            //NSLog(@"2");
            //拍照
            // 检查设备是否可用
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                
                // 创建UIImagePickerController对象
                imgPC = [[UIImagePickerController alloc]init];
                // 设置源类型（确定是调用摄像头还是调用图片库）
                imgPC.sourceType = UIImagePickerControllerSourceTypeCamera;
                // 设置允许编辑
                imgPC.mediaTypes = @[(NSString*)kUTTypeImage];
                imgPC.allowsEditing = YES;
                // 设置代理对象
                imgPC.delegate = self;
                
                // 弹出模式视图控制器
                [self presentViewController:imgPC animated:YES completion:nil];
            }
            
        }break;
        case 2:{
            //NSLog(@"3");
            //从相册选择
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                
                imgPC = [[UIImagePickerController alloc]init];
                imgPC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                // 媒体类型——相册
                imgPC.mediaTypes = @[(NSString*)kUTTypeImage];
                imgPC.allowsEditing = YES;
                imgPC.delegate = self;
                
                [self presentViewController:imgPC animated:YES completion:nil];
            }
        }break;
        default:
            break;
    }
}

#pragma mark - UIImagePickerControllerDelegate

// 拍摄完成后要执行的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    // 处理照片
    if ([mediaType isEqualToString:(NSString*)kUTTypeImage]) {
        UIImage *origImg;//原始图片
        UIImage *editedImg;//编辑后的图片
        // 获取原始图片
        origImg = [info objectForKey:UIImagePickerControllerOriginalImage];
        // 获取编辑后的图片
        editedImg = [info objectForKey:UIImagePickerControllerEditedImage];
        
        if (editedImg) {
            image = editedImg;
            changed = YES;
            addChanged = YES;
        }else{
            image = origImg;
            changed = YES;
            addChanged = YES;
        }
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
            // 保存到相机胶卷（相册图库）
            UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
        }
        mainImage.image = image;
        NSData *imageData = UIImagePNGRepresentation(image);
        imgFileByte = [imageData hexadecimalString];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

// 点击cancel后执行的方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}


// 获取当前时间
- (NSString*)getCurrentDateTime {
    NSDate *senddate=[NSDate date];
    
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    
    [dateformatter setDateFormat:@"YYYYMMddhhmmss"];
    
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    
    //NSLog(@"locationString:%@",locationString);
    
    return locationString;
}

-(void)dealloc{
    [getMainRequest cancel];
    postHud = nil;
    [postSaveRequest cancel];
    [postUploadFile cancel];
}

@end
